package weixiu;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class RepairPanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;
    private JPanel topPanel;
    private JButton btnViewLockers;
    private JButton btnViewComplaints;
    private JScrollPane scrollPane;

    private enum ViewMode { LOCKERS, COMPLAINTS }

    private ViewMode currentMode = ViewMode.LOCKERS;

    public RepairPanel() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        JLabel title = new JLabel("维修人员处理模块", SwingConstants.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 24));
        title.setBorder(BorderFactory.createEmptyBorder(20, 0, 10, 0));
        add(title, BorderLayout.NORTH);

        // 顶部按钮栏
        topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        btnViewLockers = new JButton("查看故障柜门");
        btnViewComplaints = new JButton("查看投诉记录");

        btnViewLockers.addActionListener(e -> {
            currentMode = ViewMode.LOCKERS;
            refreshTable();
        });

        btnViewComplaints.addActionListener(e -> {
            currentMode = ViewMode.COMPLAINTS;
            refreshTable();
        });

        topPanel.add(btnViewLockers);
        topPanel.add(btnViewComplaints);
        add(topPanel, BorderLayout.SOUTH);

        // 表格初始化
        model = new DefaultTableModel();
        table = new JTable(model);
        table.setRowHeight(35);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
        scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        refreshTable();
    }

    private void refreshTable() {
        if (currentMode == ViewMode.LOCKERS) {
            loadFaultyLockers();
        } else {
            loadComplaints();
        }
    }

    // 加载“故障”柜门
    private void loadFaultyLockers() {
        model.setDataVector(new Object[][]{}, new Object[]{"柜门编号", "当前状态", "维修"});
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id, status FROM lockers WHERE status = '故障'";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                int id = rs.getInt("id");
                String status = rs.getString("status");
                model.addRow(new Object[]{id, status, "维修"});
            }

            rs.close();
            ps.close();

            // 设置按钮渲染器和编辑器
            TableColumn column = table.getColumnModel().getColumn(2);
            column.setCellRenderer(new ButtonRenderer());
            column.setCellEditor(new ButtonEditor(new JCheckBox()));

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载故障柜门失败：" + e.getMessage());
        }
    }

    // 加载“待处理”投诉记录
    private void loadComplaints() {
        model.setDataVector(new Object[][]{}, new Object[]{"编号", "柜子ID", "原状态", "原因", "状态", "时间", "联系方式"});
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id, locker_id, original_status, reason, status, report_time, phone FROM complaints WHERE status = '待处理'";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                model.addRow(new Object[]{
                        rs.getInt("id"),
                        rs.getInt("locker_id"),
                        rs.getString("original_status"),
                        rs.getString("reason"),
                        rs.getString("status"),
                        rs.getTimestamp("report_time"),
                        rs.getString("phone")
                });
            }

            rs.close();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载投诉记录失败：" + e.getMessage());
        }
    }

    // 渲染按钮
    class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            setText((value == null) ? "维修" : value.toString());
            return this;
        }
    }

    // 编辑器 - 维修按钮
    class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private int currentRow;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton("维修");
            button.setOpaque(true);
            button.addActionListener(e -> repairLocker(currentRow));
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            currentRow = row;
            return button;
        }
    }

    // 维修操作
    private void repairLocker(int row) {
        int lockerId = (int) model.getValueAt(row, 0);

        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);

            // 查询投诉记录
            String queryComplaint = "SELECT id, phone, original_status FROM complaints " +
                    "WHERE locker_id = ? AND status = '待处理' ORDER BY report_time DESC LIMIT 1";
            PreparedStatement ps1 = conn.prepareStatement(queryComplaint);
            ps1.setInt(1, lockerId);
            ResultSet rs = ps1.executeQuery();

            String originalStatus = "空闲";
            String phone = "未知";
            int complaintId = -1;

            if (rs.next()) {
                complaintId = rs.getInt("id");
                originalStatus = rs.getString("original_status");
                phone = rs.getString("phone");
            }

            rs.close();
            ps1.close();

            // 更新柜子状态
            String updateLocker = "UPDATE lockers SET status = ? WHERE id = ?";
            PreparedStatement ps2 = conn.prepareStatement(updateLocker);
            ps2.setString(1, originalStatus);
            ps2.setInt(2, lockerId);
            ps2.executeUpdate();
            ps2.close();

            // 更新投诉状态为“已处理”
            if (complaintId != -1) {
                String updateComplaint = "UPDATE complaints SET status = '已处理' WHERE id = ?";
                PreparedStatement ps3 = conn.prepareStatement(updateComplaint);
                ps3.setInt(1, complaintId);
                ps3.executeUpdate();
                ps3.close();
            }

            conn.commit();

            JOptionPane.showMessageDialog(this,
                    "柜门 " + lockerId + " 已维修，恢复状态为：" + originalStatus + "\n请通知用户：" + phone,
                    "维修完成", JOptionPane.INFORMATION_MESSAGE);

            refreshTable();

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "维修失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
